const argv = process.argv;

// 是否是启动服务还是发布任务，默认为启动服务true
const isLaunched = argv.indexOf("startOrRestart") > -1;
const index = argv.indexOf("--env");
let env = index > -1 ? argv[index + 1] : "development";
if (!isLaunched) {
  env = argv[1];
}
const { name, config = {}, pkg = {} } = require("@colpu/cli/config")(__dirname);
const PRODUCTION_DIR = `/var/www/${name}`;
const command = [
  "git fetch",
  "npm install --no-lockfile --production",
  `pm2 startOrRestart launched.config.js --env ${env}`,
];

function curlBash() {
  const command = [];
  return command;
}
const setDeployENV = () => {
  const map = {};
  map[env] = Object.assign(
    {
      repo: pkg.repository.url,
      ref: "origin/master",
      host: ["127.0.0.1"],
      user: "root",
      path: PRODUCTION_DIR,
    },
    {
      "pre-setup": `mkdir -p ${PRODUCTION_DIR}`,
      "post-deploy": command.concat(curlBash()).join(" && "),
      env: {
        NODE_ENV: env,
      },
    },
    config.deploy
  );
  return map;
};
const LAUNCHED = {};
if (isLaunched) {
  const logsPath =
    env == "local" ? "/Users/colpu/Documents/tmp/" : "/var/logs/";
  LAUNCHED.apps = [
    {
      name,
      script: "./node_modules/@colpu/cli/script/service.js",
      cwd: "./",
      instances: 2,
      max_restarts: 2,
      min_uptime: "1h",
      exec_mode: "cluster",
      max_memory_restart: "1024M",
      env_local: {
        NODE_ENV: "local",
      },
      env_preview: {
        NODE_ENV: "preview",
      },
      env_release: {
        NODE_ENV: "release",
      },
      env_production: {
        NODE_ENV: "production",
      },
      instance_var: "INSTANCE_ID",
      error_file: `${logsPath}${name}_err.log`,
      out_file: `${logsPath}${name}_out.log`,
      merge_logs: true,
      log_date_format: "YYYY-MM-DD HH:mm Z",
    },
  ];

} else {
  LAUNCHED.deploy = setDeployENV();
}
module.exports = LAUNCHED;
